<template>
  <div class="shop-create-container">
    <div class="page-header">
      <h2>新增商家</h2>
    </div>

    <el-card class="form-card">
      <el-form
          ref="shopFormRef"
          :model="shopForm"
          :rules="formRules"
          label-width="120px"
          size="default"
      >
        <!-- 商家类型 -->
        <el-form-item label="商家类型" prop="businessType">
          <el-select v-model="shopForm.businessType" placeholder="请选择商家类型">
            <el-option label="餐饮美食" value="food"></el-option>
            <el-option label="零售百货" value="retail"></el-option>
            <el-option label="休闲娱乐" value="entertainment"></el-option>
          </el-select>
        </el-form-item>

        <!-- 门店名称 -->
        <el-form-item label="门店名称" prop="shopName">
          <el-input v-model="shopForm.shopName" placeholder="请输入门店名称"></el-input>
        </el-form-item>

        <!-- 门店电话 -->
        <el-form-item label="门店电话" prop="phone">
          <el-input v-model="shopForm.phone" placeholder="请输入门店电话"></el-input>
        </el-form-item>

        <!-- 负责人 -->
        <el-form-item label="负责人" prop="contactPerson">
          <el-input v-model="shopForm.contactPerson" placeholder="请输入负责人"></el-input>
        </el-form-item>

        <!-- 负责人电话 -->
        <el-form-item label="负责人电话" prop="contactPhone">
          <el-input v-model="shopForm.contactPhone" placeholder="请输入负责人电话"></el-input>
        </el-form-item>

        <!-- 门店地区（省市区联动） -->
        <el-form-item label="门店地区" prop="region">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-select
                  v-model="shopForm.provinceId"
                  placeholder="请选择省份"
                  @change="handleProvinceChange"
                  clearable
              >
                <el-option
                    v-for="item in provinces"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select
                  v-model="shopForm.cityId"
                  placeholder="请选择城市"
                  @change="handleCityChange"
                  :disabled="!shopForm.provinceId"
                  clearable
              >
                <el-option
                    v-for="item in cities"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select
                  v-model="shopForm.districtId"
                  placeholder="请选择区县"
                  :disabled="!shopForm.cityId"
                  clearable
              >
                <el-option
                    v-for="item in districts"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 详细地址 -->
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="shopForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>

        <!-- 门店坐标 -->
        <el-form-item label="门店坐标" prop="coordinate">
          <el-input v-model="shopForm.coordinate" placeholder="点击地图选择坐标" readonly></el-input>
        </el-form-item>

        <!-- 门店地图 -->
        <el-form-item label="门店地图">
          <div id="mapContainer" class="map-container"></div>
        </el-form-item>

        <!-- 门店图片上传 -->
        <el-form-item label="门店图片">
          <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleImageUploadSuccess"
              :file-list="imageFileList"
              list-type="picture-card"
              :headers="uploadHeaders"
          >
            <template #default>
              <el-icon><Plus /></el-icon>
              <div class="el-upload__text">上传图片</div>
            </template>
            <template #file="{ file }">
              <img v-if="file.url" :src="file.url" class="upload-image" alt="" />
              <el-icon class="el-upload__delete-icon" @click="handleRemoveImage(file)"><Delete /></el-icon>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 门店Logo上传 -->
        <el-form-item label="门店Logo">
          <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleLogoUploadSuccess"
              :file-list="logoFileList"
              list-type="picture-card"
              :limit="1"
              :on-exceed="handleExceed"
              :headers="uploadHeaders"
          >
            <template #default>
              <el-icon><Plus /></el-icon>
              <div class="el-upload__text">上传Logo</div>
            </template>
            <template #file="{ file }">
              <img v-if="file.url" :src="file.url" class="upload-image" alt="" />
              <el-icon class="el-upload__delete-icon" @click="handleRemoveLogo(file)"><Delete /></el-icon>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 商家简介 -->
        <el-form-item label="商家简介" prop="description">
          <el-input v-model="shopForm.description" placeholder="请输入商家简介" type="textarea" rows="4"></el-input>
        </el-form-item>

        <!-- 排序 -->
        <el-form-item label="排序">
          <el-select v-model="shopForm.sort" placeholder="请选择排序">
            <el-option label="升序" value="asc"></el-option>
            <el-option label="降序" value="desc"></el-option>
          </el-select>
        </el-form-item>

        <!-- 营业时间 -->
        <el-form-item label="营业时间" prop="businessHours">
          <el-input v-model="shopForm.businessHours" placeholder="请输入营业时间（例如：09:00-22:00）"></el-input>
        </el-form-item>

        <!-- 门店状态 -->
        <el-form-item label="门店状态">
          <el-radio-group v-model="shopForm.status">
            <el-radio label="1">开启</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElLoading } from 'element-plus';
import axios from 'axios';

// 路由实例
const router = useRouter();
// 表单引用
const shopFormRef = ref(null);

// 表单数据（与数据库字段映射）
const shopForm = reactive({
  businessType: '',         // 商家类型
  shopName: '',             // 门店名称（对应 lbs_store.store_name）
  phone: '',                // 门店电话（对应 lbs_store.store_phone）
  contactPerson: '',        // 负责人（对应 lbs_store.store_head_name）
  contactPhone: '',         // 负责人电话（对应 lbs_store.store_head_phone）
  provinceId: '',           // 省份ID（对应 lbs_store.province_id）
  cityId: '',               // 城市ID（对应 lbs_store.city_id）
  districtId: '',           // 区县ID（对应 lbs_store.area_id）
  address: '',              // 详细地址（对应 lbs_store.store_location）
  coordinate: '',           // 坐标（后续拆分为经纬度）
  description: '',          // 商家简介（对应 lbs_store.store_introduction）
  sort: 'asc',              // 排序（对应 lbs_store.sort）
  businessHours: '',        // 营业时间（对应 lbs_store.trade_time）
  status: '1'               // 门店状态（1=开启，0=禁用，对应 lbs_store.store_status）
});

// 表单验证规则
const formRules = reactive({
  businessType: [{ required: true, message: '请选择商家类型', trigger: 'change' }],
  shopName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入门店电话', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入负责人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  provinceId: [{ required: true, message: '请选择省份', trigger: 'change' }],
  cityId: [{ required: true, message: '请选择城市', trigger: 'change' }],
  districtId: [{ required: true, message: '请选择区县', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  coordinate: [{ required: true, message: '请选择门店坐标', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商家简介', trigger: 'blur' }],
  businessHours: [{ required: true, message: '请输入营业时间', trigger: 'blur' }]
});

// 省市区数据（从后端加载）
const provinces = ref([]);    // 省份列表
const cities = ref([]);      // 城市列表
const districts = ref([]);   // 区县列表

// 图片上传相关
const imageFileList = ref([]);  // 门店图片列表
const logoFileList = ref([]);   // Logo图片列表
const uploadHeaders = ref({
  'Authorization': 'Bearer ' + localStorage.getItem('token')  // 上传接口的身份认证
});

// 加载省份列表（页面初始化时）
onMounted(() => {
  loadProvinces();
  initMap();
});

// 加载所有省份
const loadProvinces = () => {
  axios.get('/api/dict/province')
      .then(res => {
        if (res.data.code === 200) {
          provinces.value = res.data.data;
        } else {
          ElMessage.error('加载省份失败：' + res.data.message);
        }
      })
      .catch(err => {
        ElMessage.error('省份接口请求失败');
        console.error(err);
      });
};

// 省份选择变化时加载城市
const handleProvinceChange = (provinceId) => {
  if (!provinceId) return;

  shopForm.cityId = '';
  shopForm.districtId = '';
  districts.value = [];

  axios.get(`/api/dict/city?provinceId=${provinceId}`)
      .then(res => {
        if (res.data.code === 200) {
          cities.value = res.data.data;
        } else {
          ElMessage.error('加载城市失败：' + res.data.message);
        }
      })
      .catch(err => {
        ElMessage.error('城市接口请求失败');
        console.error(err);
      });
};

// 城市选择变化时加载区县
const handleCityChange = (cityId) => {
  if (!cityId) return;

  shopForm.districtId = '';

  axios.get(`/api/dict/district?cityId=${cityId}`)
      .then(res => {
        if (res.data.code === 200) {
          districts.value = res.data.data;
        } else {
          ElMessage.error('加载区县失败：' + res.data.message);
        }
      })
      .catch(err => {
        ElMessage.error('区县接口请求失败');
        console.error(err);
      });
};

// 图片上传成功回调
const handleImageUploadSuccess = (response, file) => {
  if (response.code === 200) {
    // 假设接口返回图片ID和URL
    file.url = response.data.url;
    file.id = response.data.id;
    imageFileList.value.push(file);
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败：' + response.message);
  }
};

// Logo上传成功回调
const handleLogoUploadSuccess = (response, file) => {
  if (response.code === 200) {
    file.url = response.data.url;
    file.id = response.data.id;
    logoFileList.value = [file];  // 只保留一张
    ElMessage.success('Logo上传成功');
  } else {
    ElMessage.error('Logo上传失败：' + response.message);
  }
};

// 移除图片
const handleRemoveImage = (file) => {
  imageFileList.value = imageFileList.value.filter(item => item.uid !== file.uid);
};

// 移除Logo
const handleRemoveLogo = (file) => {
  logoFileList.value = [];
};

// 超出上传限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传一张Logo图片');
};

// 初始化地图
const initMap = () => {
  nextTick(() => {
    if (window.BMapGL) {
      // 初始化百度地图
      const map = new window.BMapGL.Map("mapContainer");
      const point = new window.BMapGL.Point(116.4074, 39.9024); // 北京中心点
      map.centerAndZoom(point, 15);
      map.enableScrollWheelZoom(true); // 启用滚轮缩放

      // 地图点击事件 - 获取坐标
      map.addEventListener('click', (e) => {
        shopForm.coordinate = `${e.latlng.lat}, ${e.latlng.lng}`;
      });

      // 添加地图控件
      map.addControl(new window.BMapGL.NavigationControl());
    } else {
      ElMessage.error('百度地图加载失败，请检查网络或刷新页面');
    }
  });
};

// 表单提交
const handleSubmit = () => {
  shopFormRef.value.validate((valid) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        text: '提交中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      // 处理表单数据（与数据库字段映射）
      const submitData = {
        store_name: shopForm.shopName,
        store_phone: shopForm.phone,
        store_head_name: shopForm.contactPerson,
        store_head_phone: shopForm.contactPhone,
        province_id: shopForm.provinceId,
        city_id: shopForm.cityId,
        area_id: shopForm.districtId,
        store_location: shopForm.address,
        // 拆分经纬度
        store_longitude: shopForm.coordinate.split(',')[1]?.trim() || '',
        store_latitude: shopForm.coordinate.split(',')[0]?.trim() || '',
        store_images_id: imageFileList.value.map(item => item.id).join(','), // 图片ID逗号分隔
        store_logo: logoFileList.value[0]?.id || '',
        store_introduction: shopForm.description,
        sort: shopForm.sort === 'asc' ? 0 : 1, // 假设数据库用0/1表示排序
        trade_time: shopForm.businessHours,
        store_status: shopForm.status === '1' ? 0 : -1 // 数据库状态：0=开启，-1=禁用
      };

      // 调用后端新增接口
      axios.post('/api/store/create', submitData)
          .then(res => {
            loading.close();
            if (res.data.code === 200) {
              ElMessage.success('门店新增成功');
              router.push('/shop/list'); // 跳转到列表页
            } else {
              ElMessage.error('提交失败：' + res.data.message);
            }
          })
          .catch(err => {
            loading.close();
            ElMessage.error('接口请求失败');
            console.error(err);
          });
    }
  });
};

// 重置表单
const handleReset = () => {
  shopFormRef.value.resetFields();
  imageFileList.value = [];
  logoFileList.value = [];
  shopForm.coordinate = '';
};
</script>

<style scoped>
.shop-create-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2329;
}

.form-card {
  padding: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.map-container {
  width: 100%;
  height: 350px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>